<?php
namespace app\admin\controller;

use think\auth\Auth;
use think\Loader;
use think\Cache;
use think\Controller;
use think\Db;

/**
 * 后台公用基础控制器
 * Class AdminBase
 * @package app\common\controller
 */
class BaseController extends Controller {

	protected $site_config;

	protected function _initialize() {
		parent::_initialize();
		 $this->assign('menu',db('menu')->select());
		// 判断登录状态
		/*$user = Db::name('user')->field('session_id')->where('id', session('ADMIN.id'))->find();
		if ($user['session_id'] != session_id()) {
			//session('ADMIN', null);
			$this->success('该账号已在别处登录！', 'login/index');
		}*/
		$user=Db::name('user')->field('session_id')->where('id',session('ADMIN.id'))->find();
			      if($user['session_id']!=session_id()){
	      	
	      	$this->success('该账户已在别处登录','login/index');
	      }
	}


	/**
	 * 通用状态设置
	 * 禁用、启用都是调用这个内部方法
	 * @return mixed
	 */
	public function status() {
		$table = input('param.table', strtolower(request()->controller()));
		$field = input('param.field', 'status');
		$ids = input('param.ids/a') ? input('param.ids/a') : input('param.id/a');
		$val = input('param.val', 1);
		$id=input("param.id_name")?input("param.id_name"):"id";
		
		if (empty($ids)) {
			return $this->error('参数传递错误[1]！');
		}
		if (empty($table)) {
			return $this->error('参数传递错误[2]！');
		}
		$res = db($table)->where($id, 'in', $ids)->setField($field, $val);
		if ($res === false) {
			$this->error('设置失败');
		}
		$this->success('设置成功');
	}

	/**
	 * 通用删除
	 * 单纯的记录删除
	 * @return mixed
	 */
	public function delete() {
		$ids = input('param.ids/a') ? input('param.ids/a') : input('param.id/a');
		$table = input('param.table', strtolower(request()->controller()));
		$id=input("param.id_name")?input("param.id_name"):"id";
		// 获取主键
		$res = db($table)->where($id, 'in', $ids)->delete();
		if ($res === false) {
			$this->error('删除失败');
		}
		$this->success('删除成功');
	}

	/**
	 * 通用排序
	 * @return mixed
	 */
	public function sorts() {
		$table = input('param.table', strtolower(request()->controller()));
		$field = input('param.field/s', 'sort');
		$ids = input('param.ids/d') ? input('param.ids/d') : input('param.id/d');
		$val = input('param.val/d', 0);
		$res = db($table)->where('id', 'in', $ids)->setField($field, $val);
		if ($res === false) {
			$this->error('排序失败');
		}
		$this->success('排序成功');
	}
		//上传图片
	public function upload(){
		$file = request()->file('file');
		$info = $file -> move(ROOT_PATH . DS . 'uploads' );
		if ($info) {
			$result['code'] = 1;
			$result['msg'] = '上传成功！';
			$result['src'] = '/uploads/' . str_replace('\\', '/', $info -> getSaveName());
		} else {
			$result['code'] = 0;
			$result['msg'] = $file -> getError();
		}
		return json($result);
	}
}
